package com.sophic_tech.hkb.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sophic_tech.hkb.entity.AccountModel;

import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class JWTUtils {
    static Date date = Date.from(new Date().toInstant());
    static String year = date.toInstant().atZone(ZoneId.systemDefault()).getYear() + "";
    private static final String SECRET_KEY = "Sophic_tech-hkb" + "_" + year;
    static String tokenExpireTime;

    public static String getToken( AccountModel model) {
        Calendar instance = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.systemDefault()));
        instance.add(Calendar.DATE, 7);
        tokenExpireTime = instance.getTime().toString();
        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("id", model.getId())
                .withClaim("username", model.getUsername());
        return builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }

    public static DecodedJWT verify(String token) {
        if (token == null || token.isEmpty()) {
            return null;
        }
        return JWT.require(Algorithm.HMAC256(SECRET_KEY))
                .build()
                .verify(token);
    }

    public static String getExpiration() {
        return tokenExpireTime;
    }
}
